package org.easyexcel.Test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author DPF
 */
public class Lock1 {
    static boolean hasCiggrette = false;
    static boolean hasTackOver = false;

    static ReentrantLock Room = new ReentrantLock();
    static Condition CiggretteRoom = Room.newCondition();
    static Condition TackOverRoom = Room.newCondition();

    public static void main(String[] args) {

        new Thread(() -> {
            Room.lock();
            try {
                while (!hasCiggrette) {
                    System.out.printf("有烟没，没有就休息！%s%n", hasCiggrette);
                    CiggretteRoom.await();
                }
                System.out.printf("有烟了，开始工作！%s%n", hasCiggrette);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                Room.unlock();
            }
        }, "Cigrate").start();

        new Thread(() -> {
            Room.lock();
            try {
                while (!hasTackOver) {
                    System.out.printf("有外卖没，没有就休息！%s%n", hasTackOver);
                    TackOverRoom.await();
                }
                System.out.printf("有外卖了，开始工作！%s%n", hasTackOver);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                Room.unlock();
            }
        }, "TackOver").start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        new Thread(() -> {
            Room.lock();
            try {
                hasCiggrette = true;
                CiggretteRoom.signalAll();
            } finally {
                Room.unlock();
            }
        }, "送烟的").start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        new Thread(() -> {
            Room.lock();
            try {
                hasTackOver = true;
                TackOverRoom.signalAll();
            } finally {
                Room.unlock();
            }
        }, "送外卖的").start();
    }
}
